package com.bilin.coin.activity;

import android.graphics.Bitmap;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.utils.TextUtils;
import com.bilin.coin.network.callback.BitmapCallBack;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.bilin.coin.ApiConstant;
import com.bilin.coin.R;
import com.bilin.coin.bean.CommonSuccessEvent;
import com.bilin.coin.bean.LoginBean;
import com.bilin.coin.bean.RegisterTokenBean;
import com.bilin.coin.common.base.BaseAppCompatActivity;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.RetrofitConfig;
import com.bilin.coin.network.callback.CommonCallBack;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.GsonUtil;
import com.bilin.coin.utils.SharedPreferencesUtils;
import com.bilin.coin.utils.TimerUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import kt.com.bilin.coin.common.UserDataCache;
import kt.com.bilin.coin.helper.mohsi.MoshiUtils;
import okhttp3.ResponseBody;

@Route(path = "/auction/RegisterActivity")
public class RegisterActivity extends BaseAppCompatActivity {

    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_pass)
    EditText et_pass;
    @BindView(R.id.et_pass_again)
    EditText et_pass_again;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.et_invite_code)
    EditText et_invite_code;
    @BindView(R.id.bt_send)
    TextView bt_send;
    @BindView(R.id.cb_select)
    CheckBox cb_select;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.v_line)
    View v_line;
    @BindView(R.id.iv_code2)
    ImageView iv_code2;
    @BindView(R.id.et_code2)
    EditText et_code2;

    String registerToken = "";

    String address = "";

    @Override
    protected void initView() {
        v_line.setVisibility(View.GONE);
        setTitle(getResources().getString(R.string.register));
        //getRegisterToken();
        sendImgCode();
    }

    private void getRegisterToken() {
        DialogUtils.showDialogLoading(this);
        RequestUtils
                .get()
                .url("/api/user/getRegSmsToken")
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {

                    @Override
                    protected void onError(String errorMsg) {
                        showToast(errorMsg);
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        RegisterTokenBean registerTokenBean = RequestUtils.getGson().fromJson(dataJson, RegisterTokenBean.class);
                        registerToken = registerTokenBean.getToken();
                        SharedPreferencesUtils.getInstance().saveData(ApiConstant.RegisterToken, registerToken);
                        DialogUtils.dismissDialogLoading();

                    }

                    @Override
                    protected void onCallBackError(Throwable e) {
                        showMsg(e);
                        DialogUtils.dismissDialogLoading();
                    }
                });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @OnClick({R.id.bt_send, R.id.bt_confirm, R.id.ll_select_address,
            R.id.tv_protocol,R.id.et_code2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_protocol:
                jumpProtocol();
                break;
            case R.id.bt_confirm:
                if (!cb_select.isChecked()) {
                    showToast("请勾选协议");
                    return;
                }
                register();
                break;
            case R.id.bt_send:
                sendRegCode();
                break;
            case R.id.et_code2:
                sendImgCode();
                break;
            case R.id.ll_select_address:
                hideSoftKeyboard();
                break;
        }
    }

    private void jumpProtocol() {
        baseStartActivityWith("/common/WebPageLoading")
                .withString("url", RetrofitConfig.newsUrl+"0")
                .withString("title", "用户协议").navigation();
    }

    private void register() {
      /*  if (TextUtils.isEmpty(registerToken)) {
            showToast(getResources().getString(R.string.reg_token_empty));
            return;
        }*/
        String pass = et_pass.getText().toString().trim();
        String pass_again = et_pass_again.getText().toString().trim();
        String phone = et_phone.getText().toString().trim();
        String code = et_code.getText().toString().trim();
        String invite = et_invite_code.getText().toString().trim();
        //address = tv_address.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showToast(getResources().getString(R.string.phone_empty));
            return;
        }
        if (phone.length() != 11) {
            showToast("请输入11位的正确手机号");
            return;
        }
        if (TextUtils.isEmpty(pass)) {
            showToast(getResources().getString(R.string.pass_empty));
            return;
        }
        if (TextUtils.isEmpty(code)) {
            showToast(getResources().getString(R.string.sms_code_empty));
            return;
        }
        if (!pass.equals(pass_again)) {
            showToast(getResources().getString(R.string.login_two_pwd_no));
            return;
        }
     /*   if (TextUtils.isEmpty(address)) {
            showToast("请选择地区");
            return;
        }*/
        RequestUtils
                .post()
                .url("/api/user/reg")
                .addParams("code", code)
                .addParams("mobile", phone)
                .addParams("pwd", pass)
                .addParams("area", address)
                .addParams("inviteCode", invite)
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {

                    @Override
                    protected void onError(String errorMsg) {
                        showToast(errorMsg);
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        try {
                            LoginBean loginBean = RequestUtils.getGson().fromJson(dataJson, LoginBean.class);
                            String mobile = phone;
                            saveUserInfo(loginBean, mobile);
                            dataJson = dataJson == null || "".equals(dataJson) ? "{}" : dataJson;
                            UserDataCache.INSTANCE.setLoginInfo(MoshiUtils.parseObject(dataJson, kt.com.bilin.coin.bean.LoginBean.class));
                            EventBus.getDefault().post(new CommonSuccessEvent(CommonSuccessEvent.LoginSuccess));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        showToast(getResources().getString(R.string.login_register_success));
                        DialogUtils.dismissDialogLoading();
                        finish();
                    }

                    @Override
                    protected void onCallBackError(Throwable e) {
                        showMsg(e);
                        DialogUtils.dismissDialogLoading();
                    }

                });

    }

    private void saveUserInfo(LoginBean successBean, String mobile) {
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.Mobile, mobile);
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.CSRF_TOKEN, successBean.getCsrfToken());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.LoginSmsToken, successBean.getLoginSmsToken());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsHasSafeWord, successBean.getUserInfo().isHasSafeWord());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsLogin, successBean.getUserInfo().isLogin());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USER_ID,successBean.getUserInfo().getId());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USERINFO_JSON, GsonUtil.GsonString(successBean.getUserInfo()));
    }

    private void sendRegCode() {
        String phone = et_phone.getText().toString().trim();
        String code  = et_code2 .getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showToast(getResources().getString(R.string.phone_empty));
            return;
        }
        if (TextUtils.isEmpty(code)) {
            showToast("图形验证码不能为空");
            return;
        }
        DialogUtils.showDialogLoading(this);
        RequestUtils
                .post()
                .url("/api/user/sendRegCode")
                .addParams("mobile", phone)
                .addParams("code", code )
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {

                    @Override
                    protected void onError(String errorMsg) {
                        showToast(errorMsg);
                        sendImgCode();
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        TimerUtils.getInitialise().startTimer(bt_send, 120, getString(R.string.login_resend_code));
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    public void onCallBackError(Throwable e) {
                        DialogUtils.dismissDialogLoading();
                        showMsg(e);

                    }
                });
    }

    /**
     * 获取图片验证码
     *
     * @param
     */
    public void sendImgCode() {
        RequestUtils
                .getBitmap()
                .url("/api/code/captcha")
                .build()
                .compose(this.<ResponseBody>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new BitmapCallBack<Bitmap>() {
                    @Override
                    public void onCallBackNext(Bitmap result) {
                        DialogUtils.dismissDialogLoading();
                        iv_code2.setImageBitmap(result);
                    }

                    @Override
                    public void onCallBackError(Throwable e) {
                        showToast(getString(R.string.net_error));
                        DialogUtils.dismissDialogLoading();
                    }
                });

    }

}
